package com.tinyseed.emcp.crawler.base;

import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;

/**
 * @version Revision 1.0.0
 * @版权：
 * @author: Howard
 * @email:
 * @see:
 * @创建日期：2020/3/12
 * @功能说明：okhttp制造工厂
 * @begin
 * @修改记录:
 * @修改后版本 修改人        修改内容
 * @2020/3/12 wuxiran        创建
 * @end
 */
@Component
public class OkHttpClientFactory {

    public static OkHttpClient create() {

        return new OkHttpClient.Builder()
                .cookieJar(new CookieJar() {

                    // 使用ConcurrentMap存储cookie信息，因为数据在内存中，所以只在程序运行阶段有效，程序结束后即清空
                    private ConcurrentMap<String, List<Cookie>> storage = new ConcurrentHashMap<>();

                    @Override
                    public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
                        String host = url.host();
                        if (cookies != null && !cookies.isEmpty()) {
                            storage.put(host, cookies);
                        }
                    }

                    @Override
                    public List<Cookie> loadForRequest(HttpUrl url) {
                        String host = url.host();
                        List<Cookie> list = storage.get(host);
                        return list == null ? new ArrayList<>() : list;
                    }
                })
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)

                .build();

    }

}
